﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ComicViewer.IManhua;
using System.Net;
using System.IO;
using System.Windows.Threading;
using System.Threading;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Animation;

namespace ComicViewer
{
    /// <summary>
    /// Interaction logic for PageFunction3.xaml
    /// </summary>
    public partial class ViewPage : PageFunction<String>
    {
        ComicTable m_table;
        public ViewPage()
        {
            InitializeComponent();

            sb = new Storyboard();

            DoubleAnimationUsingKeyFrames frames = new DoubleAnimationUsingKeyFrames();
            Storyboard.SetTargetName(frames, ListViewPaper.Name);
            Storyboard.SetTargetProperty(frames, new PropertyPath(Canvas.LeftProperty));

            leftFrame = new EasingDoubleKeyFrame(0);
            leftFrame.KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 200));
            frames.KeyFrames.Add(leftFrame);
            sb.Children.Add(frames);


            DoubleAnimationUsingKeyFrames topframes = new DoubleAnimationUsingKeyFrames();
            Storyboard.SetTargetName(topframes, ListViewPaper.Name);
            Storyboard.SetTargetProperty(topframes, new PropertyPath(Canvas.TopProperty));

            topFrame = new EasingDoubleKeyFrame(0);
            topFrame.KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 200));
            topframes.KeyFrames.Add(topFrame);
            sb.Children.Add(topframes);
            sb.Completed += new EventHandler(sb_Completed);
            this.Resources.Add("SBSB", sb);

            m_table = Application.Current.Properties["Table"] as ComicTable;
            this.Loaded += new RoutedEventHandler(ViewPage_Loaded);
        }

        void ViewPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (m_table.Pages.Count == 0)
            {
               new IManhuaProxy().GetPages(m_table);
            }

            foreach (ComicPage page in m_table.Pages)
            {
                //Border border = new Border();
                //border.BorderBrush = new SolidColorBrush(Colors.White);
                //border.BorderThickness = new Thickness(5);
                //Button button = new Button();
                //Image image = new Image();
                //button.Content = image;
                //button.Width = 120;
                //button.Height = 240;
                //border.Child = button;
                
                //PicContainer.Children.Add(border);
                //image.Tag = page;
                //button.Click += new RoutedEventHandler(button_Click);

                WebClient client = new WebClient();
                client.Headers.Add("Referer", page.ReferUrl);
                client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
                client.DownloadDataAsync(page.PicUri, page);
            }

            ListViewPaper.ItemsSource = m_table.Pages;
            Canvas.SetTop(ListViewPaper, 0);
            Canvas.SetLeft(ListViewPaper, 0);

            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_table.Pages[0].PicUri);
            //request.Referer = m_table.Pages[0].ReferUrl;
            //request.BeginGetResponse(OnAsyncCallback, request);
        }

        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                ComicPage page = e.UserState as ComicPage;
                
                Stream stream = new MemoryStream(e.Result);
                BitmapImage source = new BitmapImage();
                source.BeginInit();
                source.StreamSource = stream;
                source.EndInit();
                page.Source = source;
            }
            else
            {
                ComicPage page = e.UserState as ComicPage;
                
                WebClient client = new WebClient();
                client.Headers.Add("Referer", page.ReferUrl);
                client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted2);
                client.DownloadDataAsync(page.PicUriPng, page);
            }
        }

        void client_DownloadDataCompleted2(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                ComicPage page = e.UserState as ComicPage;

                Stream stream = new MemoryStream(e.Result);
                BitmapImage source = new BitmapImage();
                source.BeginInit();
                source.StreamSource = stream;
                source.EndInit();
                page.Source = source;
            }
            else
            {
            }
        }
        
        bool m_isMoving = false;
        Point m_startMovePos;
        Point m_imageStartPos;

        Storyboard sb;
        EasingDoubleKeyFrame leftFrame;
        EasingDoubleKeyFrame topFrame;
        long dTick;

        void sb_Completed(object sender, EventArgs e)
        {
        }

        private void GridMask_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            m_imageStartPos = new Point(
                Canvas.GetLeft(ListViewPaper),
                Canvas.GetTop(ListViewPaper));
            m_startMovePos = e.GetPosition(GridMask);
            dTick = DateTime.Now.Ticks;
            Cursor = Cursors.Hand;
            m_isMoving = true;
        }

        private void GridMask_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //if (e.RightButton == MouseButtonState.Released)
            //{
                if (m_isMoving)
                {
                    Point currentPos = e.GetPosition(GridMask);
                    /*<Storyboard x:Key="Storyboard1">
                <Int32AnimationUsingKeyFrames Storyboard.TargetProperty="(Grid.Row)" Storyboard.TargetName="listView">
                    <EasingInt32KeyFrame KeyTime="0:0:0.3" Value="1"/>
                    <EasingInt32KeyFrame KeyTime="0:0:0.7" Value="3"/>
                </Int32AnimationUsingKeyFrames>
            </Storyboard>*/

                    //leftFrame.Value = Canvas.GetLeft(ListViewPaper) + (currentPos.X - m_startMovePos.X) * 0.2;
                    //topFrame.Value = Canvas.GetTop(ListViewPaper) + (currentPos.Y - m_startMovePos.Y) * 0.2;
                    //leftFrame.KeyTime = KeyTime.FromTimeSpan(new TimeSpan((long)((DateTime.Now.Ticks - dTick) * 0.5)));
                    //topFrame.KeyTime = leftFrame.KeyTime;
                    //sb.Begin();
                }
                m_isMoving = false;
                Cursor = Cursors.Arrow;
            //}

        }

        private void GridMask_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_isMoving)
            {
                sb.Stop();
                Point currentPos = e.GetPosition(GridMask);
                Canvas.SetTop(ListViewPaper, m_imageStartPos.Y + currentPos.Y - m_startMovePos.Y);
                Canvas.SetLeft(ListViewPaper, m_imageStartPos.X + currentPos.X - m_startMovePos.X);
            }
        }
    }
}
